package com.malex.mxtracker;

import org.apache.commons.net.smtp.SMTPClient;
import org.apache.commons.net.smtp.SMTPReply;
import org.apache.commons.net.smtp.SimpleSMTPHeader;

import java.io.IOException;
import java.io.Writer;

/**
 * @author Manusovich Alexander
 */
public class MailSender {
    public static void send(String message) {
        SMTPClient client = new SMTPClient("UTF-8");
        client.setDefaultTimeout(10 * 1000);

        client.setRequireStartTLS(false); // requires STARTTLS
//                client.setUseStartTLS(true); // tries STARTTLS, but falls back if not supported
        client.setUseAuth(true); // use SMTP AUTH
//                client.setAuthMechanisms("LOGIN"); // sets AUTH mechanisms e.g. LOGIN

        try {
            String from = "ksd2@gidroogk.ru";
            String to = "amanusovich@qulix.com";
            String subject = "subject";

            client.connect("192.168.8.72", 25);
            checkReply(client);

            client.login();

//                    client.login("localhost", "manusovich.mobile@gmail.com", "500817viky9");
            checkReply(client);

            client.setSender(from);
            checkReply(client);
            client.addRecipient(to);
            checkReply(client);

            Writer writer = client.sendMessageData();

            if (writer != null) {
                SimpleSMTPHeader header = new SimpleSMTPHeader(from, to, subject);
                writer.write(header.toString());
                writer.write(message);
                writer.close();
                client.completePendingCommand();
                checkReply(client);
            }

            client.logout();
            client.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void checkReply(SMTPClient sc) throws IOException {
        if (SMTPReply.isNegativeTransient(sc.getReplyCode())) {
            sc.disconnect();
            throw new IOException("Transient SMTP error " + sc.getReplyCode());
        } else if (SMTPReply.isNegativePermanent(sc.getReplyCode())) {
            sc.disconnect();
            throw new IOException("Permanent SMTP error " + sc.getReplyCode());
        }
    }

}
